package com.zbkj.crmeb.supplier.controller;

import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.constants.Constants;
import com.crmeb.core.common.CommonResult;
import com.github.pagehelper.PageInfo;
import com.github.pagehelper.util.StringUtil;
import com.zbkj.crmeb.chant.model.ChannelMerchant;
import com.zbkj.crmeb.chant.service.IChannelMerchantService;
import com.zbkj.crmeb.enums.BrandTypeEnum;
import com.zbkj.crmeb.merchant.admin.controller.AdminBaseController;
import com.zbkj.crmeb.store.dto.StoreBrandDTO;
import com.zbkj.crmeb.store.model.ChannelStoreBrandConfig;
import com.zbkj.crmeb.store.model.StoreBrand;
import com.zbkj.crmeb.store.model.StoreProduct;
import com.zbkj.crmeb.store.request.CateHotRequest;
import com.zbkj.crmeb.store.request.StoreBrandAuditRequest;
import com.zbkj.crmeb.store.request.StoreBrandRequest;
import com.zbkj.crmeb.store.response.StoreBrandResponse;
import com.zbkj.crmeb.store.service.ChannelStoreBrandConfigService;
import com.zbkj.crmeb.store.service.StoreBrandAuditService;
import com.zbkj.crmeb.store.service.StoreBrandService;
import com.zbkj.crmeb.store.service.StoreProductService;
import com.zbkj.crmeb.system.model.SystemConfig;
import com.zbkj.crmeb.system.service.SystemConfigService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.constraints.NotEmpty;
import java.util.Date;
import java.util.List;
import java.util.Optional;
import java.util.Set;

/**
 * 品牌管理
 *
 * @author daigb
 * @Description:
 * @date 2021-04-13
 */
@RestController
@RequestMapping("api/admin/supplier/store/brand")
@Api(tags = "供应商品牌管理")
class SupplierStoreBrandController extends AdminBaseController {
    @Autowired
    StoreBrandService storeBrandService;
    @Autowired
    StoreProductService storeProductService;
    @Autowired
    ChannelStoreBrandConfigService channelStoreBrandConfigService;
    @Autowired
    private IChannelMerchantService channelMerchantService;
    @Autowired
    private SystemConfigService systemConfigService;
    @Autowired
    private StoreBrandAuditService storeBrandAuditService;

    /**
     * 分页查询
     *
     * @param @param  storeBrandRequest
     * @param @return
     * @return CommonResult<Object>
     * @throws
     * @Description:
     * @author daigb
     */
    @ApiOperation(value = "自建分页")
    @PostMapping("/inside/page")
    public CommonResult<Object> insidePageEntity(@RequestBody StoreBrandRequest storeBrandRequest, HttpServletRequest servletRequest) {
        int merId = getMerId(servletRequest);
        storeBrandRequest.setCreateUserId(merId);
        return CommonResult.success(storeBrandService.pageEntity(storeBrandRequest));
    }

    /**
     * 新增
     *
     * @param @param  storeBrandDTO
     * @param @return
     * @return CommonResult<Object>
     * @throws
     * @Description:
     * @author daigb
     */
    @ApiOperation(value = "新增")
    @PostMapping("/save")
    public CommonResult<Object> save(@RequestBody StoreBrandDTO storeBrandDTO, HttpServletRequest servletRequest) {
        int merId = getMerId(servletRequest);
        if (null == storeBrandDTO.getType()) {
            return CommonResult.validateFailed("品牌类型不能为空");
        }
        if (BrandTypeEnum.XUNWU != BrandTypeEnum.valueOf(storeBrandDTO.getType()) && null == storeBrandDTO.getSuperId()) {
            return CommonResult.validateFailed("关联寻物品牌不能为空");
        }
        if (StringUtil.isEmpty(storeBrandDTO.getEnName())) {
            return CommonResult.validateFailed("品牌名称不能为空");
        }
        StoreBrand check = storeBrandService.getBrandName(storeBrandDTO.getEnName(), merId);
        if (null != check) {
            return CommonResult.validateFailed("品牌名称系统已存在");
        }
        storeBrandDTO.setIdentityType(2);
        storeBrandDTO.setCreateUserId(merId);
        return CommonResult.success(storeBrandService.saveEntity(storeBrandDTO));
    }

    @ApiOperation(value = "修改")
    @PutMapping("/update")
    public CommonResult<Object> update(@RequestBody StoreBrandDTO storeBrandDTO, HttpServletRequest servletRequest) {
        int merId = getMerId(servletRequest);
        if (null == storeBrandDTO.getId()) {
            return CommonResult.validateFailed("品牌ID不能为空");
        }
        if (null == storeBrandDTO.getType()) {
            return CommonResult.validateFailed("品牌类型不能为空");
        }
        if (BrandTypeEnum.XUNWU != BrandTypeEnum.valueOf(storeBrandDTO.getType()) && null == storeBrandDTO.getSuperId()) {
            return CommonResult.validateFailed("关联寻物品牌不能为空");
        }
        if (StringUtil.isEmpty(storeBrandDTO.getEnName())) {
            return CommonResult.validateFailed("品牌名称不能为空");
        }
        StoreBrand check = storeBrandService.getBrandName(storeBrandDTO.getEnName(), merId);
        if (null != check && !check.getId().equals(storeBrandDTO.getId())) {
            return CommonResult.validateFailed("品牌名称系统已存在");
        }
        return CommonResult.success(storeBrandService.updateEntity(storeBrandDTO));
    }

    /**
     * 分页查询
     *
     * @param @param  storeBrandRequest
     * @param @return
     * @return CommonResult<Object>
     * @throws
     * @Description:
     * @author daigb
     */
    @ApiOperation(value = "分页")
    @PostMapping("/page")
    public CommonResult<Object> pageEntity(@RequestBody StoreBrandRequest storeBrandRequest, HttpServletRequest servletRequest) {
        PageInfo<StoreBrandResponse> page = storeBrandService.getMerBrandList(storeBrandRequest, getMerId(servletRequest));
        return CommonResult.success(page);
    }

    @PutMapping("/is-enabled/{id}/update/{status}")
    @ApiOperation("禁用或启用")
    public CommonResult<Object> enabled(@ApiParam(value = "主键id", required = true) @PathVariable("id") Integer id, @ApiParam(value = "启用状态 1启用 0 禁用", required = true) @PathVariable("status") Integer status) {
        return CommonResult.success(storeBrandService.update(Wrappers.<StoreBrand>lambdaUpdate()
                .eq(StoreBrand::getId, id)
                .set(StoreBrand::getStatus, status)
        ));
    }

    /**
     * 根据id删除
     *
     * @param @param  id
     * @param @return
     * @return CommonResult<Object>
     * @throws
     * @Description:
     * @author daigb
     */
    @ApiOperation(value = "根据id删除")
    @DeleteMapping("/{id}")
    public CommonResult<Object> del(@ApiParam(value = "主键id", required = true) @PathVariable("id") Integer id) {
        int count = storeProductService.count(Wrappers.lambdaQuery(StoreProduct.class).eq(StoreProduct::getBrandId, id).eq(StoreProduct::getIsDel, 0));
        if (count > 0) {
            return CommonResult.validateFailed("该品牌下有商品,删除失败!");
        }
        return CommonResult.success(storeBrandService.removeById(id));
    }

    /**
     * 批量删除
     *
     * @param @param  ids
     * @param @return
     * @return CommonResult<Object>
     * @throws
     * @Description:
     * @author daigb
     */
    @ApiOperation(value = "根据id批量删除")
    @DeleteMapping("/remove")
    public CommonResult<Object> delBatch(@NotEmpty(message = "id不能为空") @RequestBody Set<Integer> ids) {
        return CommonResult.success(storeBrandService.removeByIds(ids));
    }

    @ApiOperation(value = "开启或关闭热门品牌")
    @PutMapping("/advice")
    public CommonResult<Object> advice(@RequestBody StoreBrandDTO storeBrandDTO, HttpServletRequest servletRequest) {
        if (null == storeBrandDTO.getId() || null == storeBrandDTO.getIsAdvice()) {
            return CommonResult.validateFailed("品牌ID不能为空");
        }
        // 获取商户可见品牌
        int merId = getMerId(servletRequest);
        ChannelMerchant channelMerchant = channelMerchantService.getById(getMerId(servletRequest));
        JSONArray brandNames = JSONArray.parseArray(channelMerchant.getBrandIds());
        if (!brandNames.isEmpty() && !brandNames.contains(storeBrandDTO.getId())) {
            return CommonResult.failed();
        }
        ChannelStoreBrandConfig channelStoreBrandConfig = Optional.ofNullable(channelStoreBrandConfigService.getOne(Wrappers.lambdaQuery(ChannelStoreBrandConfig.class).eq(ChannelStoreBrandConfig::getMerId, merId)
                .eq(ChannelStoreBrandConfig::getBrandId, storeBrandDTO.getId()))).orElse(new ChannelStoreBrandConfig());
        if (channelStoreBrandConfig.getId() == null) {
            channelStoreBrandConfig.setBrandId(storeBrandDTO.getId());
            channelStoreBrandConfig.setMerId(merId);
            channelStoreBrandConfig.setCreateTime(new Date());
        }
        channelStoreBrandConfig.setIsAdvice(storeBrandDTO.getIsAdvice() == 1);
        channelStoreBrandConfig.setUpdateTime(new Date());
        return channelStoreBrandConfigService.saveOrUpdate(channelStoreBrandConfig) ? CommonResult.success() : CommonResult.failed();
    }

    @ApiOperation(value = "分类热门品牌")
    @PutMapping("/cateHot")
    public CommonResult<Object> cateHot(@RequestBody @Validated CateHotRequest request, HttpServletRequest servletRequest) {
        return channelStoreBrandConfigService.cateHot(request, getMerId(servletRequest));
    }

    @ApiOperation(value = "品牌图片展示状态")
    @GetMapping("/image")
    public CommonResult<Object> getImageStatus(HttpServletRequest servletRequest) {
        String value = systemConfigService.getValueByKey(Constants.CONFIG_KEY_APP_BRAND_IMG_STATUS + getMerId(servletRequest));
        return CommonResult.success(StringUtil.isEmpty(value) || "0".equals(value) ? false : true);
    }

    @ApiOperation(value = "开启或关闭品牌图片展示")
    @PutMapping("/image/{status}")
    public CommonResult<Object> updateImageStatus(@ApiParam(value = "状态", required = true) @PathVariable("status") Integer status, HttpServletRequest servletRequest) {
        SystemConfig config = systemConfigService.getOne(Wrappers.<SystemConfig>lambdaQuery().eq(SystemConfig::getName, Constants.CONFIG_KEY_APP_BRAND_IMG_STATUS + getMerId(servletRequest)));
        config = null == config ? new SystemConfig() : config;
        config.setName(Constants.CONFIG_KEY_APP_BRAND_IMG_STATUS + getMerId(servletRequest));
        config.setTitle("小程序品牌图片展示");
        config.setValue(status + "");
        config.setUpdateTime(new Date());

        return systemConfigService.saveOrUpdate(config) ? CommonResult.success() : CommonResult.failed();

    }

    @ApiOperation(value = "申请品牌")
    @PostMapping("/apply")
    public CommonResult<Boolean> applyBrand(@RequestBody StoreBrandAuditRequest request, HttpServletRequest servletRequest) {
        return CommonResult.success(storeBrandAuditService.applyBrand(request, getMerId(servletRequest)));
    }

}
